import axios, {AxiosInstance} from "axios";
import config from "../config";
import storage from "@/utils/stored-data";
import {getAccessToken} from '@/api/token';

const URL = config.url + "api/";
export const MsgSocketURL = URL + 'v1/message/ws';

const service: AxiosInstance = axios.create({
    baseURL: URL,
    timeout: 5000,
    headers: {},
});

service.interceptors.request.use((config) => {
    config.headers = config.headers ? config.headers : {};
    if (!storage.get('access_token')) {
        //如果为刷新token的请求则不拦截
        if (config.url === "v1/user/token/refresh") return config;

        //如果没有accessToken 也没有refreshToken，需要登录
        if (!storage.get('refresh_token')) {
            return config;
        }

        return new Promise((resolve) => {
            getAccessToken().then((res) => {
                const token = res.data.data.token;
                storage.set("access_token", token, 5);
                config.headers!['Authorization'] = `Bearer ${token}`;
                resolve(config)
            })
        })
    } else {
        if (!config.headers["Authorization"]) {
            config.headers.Authorization = `Bearer ${storage.get('access_token')}`;
        }
    }
    return config;
}), (error: any) => {
    return Promise.reject(error);
}

service.interceptors.response.use((res) => {
    return res;
}, (error) => {
    // token 过期
    if (error.response.data.code === 4010) {
        return getAccessToken().then((res) => {
            const token = res.data.data.token;
            storage.set("access_token", token, 5);
            error.config.headers.Authorization = `Bearer ${token}`;
            return service(error.config)
        })
    }
    return Promise.reject(error);
});

export default service;